package com.cheetah.cloud2020.service;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cheetah.cloud2020.entity.BaseEntity;
import com.cheetah.cloud2020.entity.SystemAdmin;
import com.cheetah.cloud2020.entity.SystemMenu;
import com.cheetah.cloud2020.entity.SystemRoleMenu;
import com.cheetah.cloud2020.mapper.SystemAdminMapper;
import com.cheetah.cloud2020.mapper.SystemRoleMapper;
import com.cheetah.cloud2020.mapper.SystemRoleMenuMapper;
import com.cheetah.cloud2020.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class SystemAdminService {

    @Autowired
    @Lazy
    private SystemAdminMapper systemAdminMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SystemRoleMapper systemRoleMapper;

    @Autowired
    private SystemRoleMenuMapper systemRoleMenuMapper;

    /**
     *
     * @param username
     * @param password
     * @return jwt token
     */
    public String login(String username, String password) {
        String token = null;
        UserDetails userDetails = loadUserByUsername(username);
        if(!passwordEncoder.matches(password,userDetails.getPassword())){
            throw new BadCredentialsException("密码不正确");
        }
//        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
//                userDetails, null, userDetails.getAuthorities());
//        SecurityContextHolder.getContext().setAuthentication(authentication);
        token = JwtTokenUtil.generateToken(userDetails);

        return token;
    }

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SystemAdmin admin = systemAdminMapper.selectOne(
                BaseEntity.<SystemAdmin> queryWrapper().eq("username", username));
        if (admin == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        String[] ids = JSONArray.parseArray(admin.getRoleIds(), Integer.TYPE)
            .stream().map(String::valueOf).distinct().toArray(String[]::new);
        return User.builder().username(username).password(admin.getPassword())
                //.roles(roleNames)
                .authorities(ids).build();
    }

    public Set<String> roleMenu(Collection<String> roleIds) {
        return this.systemRoleMenuMapper.selectByRoleIds(
                new QueryWrapper<SystemRoleMenu>()
                .in("role_id", roleIds))
                .stream().map(SystemMenu::getUrl).collect(Collectors.toSet());
    }
}
